package main

import (
	"config"
	"emulator"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"runtime"
)

var (
	cfgFilepath = ""
)

func init() {
	flag.StringVar(&cfgFilepath, "c", "", "specify the proto file path name")
}

func main() {
	flag.Parse()
	if cfgFilepath != "" {
		r := config.ParseConfigFile(cfgFilepath)
		if r != true {
			log.Fatal("can't parse configure file:", cfgFilepath)
		}
	}

	log.Println("try to start monitorService...")

	if config.LogFile != "" {
		f, err := os.OpenFile(config.LogFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
		if err != nil {
			log.Fatal("error opening log file:", err)
		}
		defer f.Close()
		log.SetOutput(f)
	}

	// subscribe.Subscribe()
	// mail.Test()
	emulator.StartEmulator()
	// log.Println("start monitor service ok!")

	if config.Daemon == "yes" {
		waitForSignal()
	} else {
		waitInput()
	}
	return
}

func waitInput() {
	var cmd string
	for {
		_, err := fmt.Scanf("%s\n", &cmd)
		if err != nil {
			//log.Println("Scanf err:", err)
			continue
		}

		switch cmd {
		case "exit", "quit":
			log.Println("exit by user")
			return
		case "gr":
			log.Println("current goroutine count:", runtime.NumGoroutine())
			break
		default:
			break
		}
	}
}

func waitForSignal() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)

	// Block until a signal is received.
	s := <-c
	fmt.Println("Got signal:", s)
}
